#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import logging

import webapp2
from webapp2_extras import sessions
from google.appengine.ext import db
from models import Survey
import jinja2
import os

jinja_environment = jinja2.Environment( loader=jinja2.FileSystemLoader(os.path.dirname(__file__)))
config = {}
config['webapp2_extras.sessions'] = {
    'secret_key': 'my-super-secret-key',
}

class BaseHandler(webapp2.RequestHandler):
    def dispatch(self):
        # Get a session store for this request.
        self.session_store = sessions.get_store(request=self.request)

        try:
            # Dispatch the request.
            webapp2.RequestHandler.dispatch(self)
        finally:
            # Save all sessions.
            self.session_store.save_sessions(self.response)

    @webapp2.cached_property
    def session(self):
        # Returns a session using the default cookie key.
        return self.session_store.get_session()


class AdminHandler(BaseHandler):
	def get(self):
		template = jinja_environment.get_template('/templates/admin.html')
		self.response.out.write(template.render({"action":"login"}))	

	def post(self):
		template = jinja_environment.get_template('/templates/admin.html')		
		action = self.request.get("action")

		if action=="login":
			password = self.request.get("password")

			if password!="bonazza198601":
				self.session['login'] = False
				self.get()
				return
			else:
				self.session['login'] = True
				action = "list"
				self.response.out.write(template.render({"action":action}))


class ListHandler(BaseHandler):
	def post(self):		
		template = jinja_environment.get_template('/templates/admin.html')		
		action = self.request.get("action")
		if self.session.get('login'):
			if action=="list":
				self.lista()
			elif action=="reset":
				s = Survey.all()
				l = s.run()
				for e in l:
					e.delete()


	def lista(self):
		template = jinja_environment.get_template('/templates/lista.html')		
		s = Survey.all()
		l = s.run()		

		total = s.count()
		s1 = [0,0,0]
		s2 = [0,0,0]
		s3 = [0,0,0]
		s4 = [0,0,0]
		s5 = [0,0,0]

		s1_p = [0.0]*3
		s2_p = [0.0]*3
		s3_p = [0.0]*3
		s4_p = [0.0]*3
		s5_p = [0.0]*3

		pg = [0.0]*3

		acao = 0
		comedia = 0
		drama = 0

		if total>0:
			for e in l:
				s1[e.sv_semana_1-1] += 1
				s2[e.sv_semana_2-1] += 1
				s3[e.sv_semana_3-1] += 1
				s4[e.sv_semana_4-1] += 1
				s5[e.sv_semana_5-1] += 1

				if e.sv_genero=="acao":
					acao+=1
				elif e.sv_genero=="comedia":
					comedia+=1
				elif e.sv_genero=="drama":
					drama+=1

			#Porcentagem em relacao a semana
			for i in range(0,3):
				s1_p[i] = float(s1[i])/total
				s2_p[i] = float(s2[i])/total
				s3_p[i] = float(s3[i])/total
				s4_p[i] = float(s4[i])/total
				s5_p[i] = float(s5[i])/total

			#Porcentagem global
			for i in range(0,3):
				pg[i] = float(s1[i]+s2[i]+s3[i]+s4[i]+s5[i])/(total*5)


		genero_fav = "acao"
		genero_fav_num = acao
		if comedia > genero_fav_num:
			genero_fav = "comedia"
			genero_fav_num = comedia
		
		if drama > genero_fav_num:
			genero_fav = "drama"
			genero_fav_num = drama

		self.response.out.write(template.render({
				"action":"list",
				"s1":s1,
				"s2":s2,
				"s3":s3,
				"s4":s4,
				"s5":s5,
				"s1_p":s1_p,
				"s2_p":s2_p,
				"s3_p":s3_p,
				"s4_p":s4_p,
				"s5_p":s5_p,
				"pg":pg,
				"total": total,
				"genero":genero_fav
			}))


app = webapp2.WSGIApplication([
    ('/admin', AdminHandler),
    ('/admin/list', ListHandler)
], config=config,debug=True)

